package com.shangdiao.sd_server.p_client.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shangdiao.sd_server.constant.Constant;
import com.shangdiao.sd_server.constant.ErrorCode;
import com.shangdiao.sd_server.constant.TableConstant;
import com.shangdiao.sd_server.generator.pojo.SdCertificate;
import com.shangdiao.sd_server.generator.pojo.SdCertificateExample;
import com.shangdiao.sd_server.generator.pojo.SdEduExp;
import com.shangdiao.sd_server.generator.pojo.SdEduExpExample;
import com.shangdiao.sd_server.generator.pojo.SdInExp;
import com.shangdiao.sd_server.generator.pojo.SdInExpExample;
import com.shangdiao.sd_server.generator.pojo.SdLabel;
import com.shangdiao.sd_server.generator.pojo.SdLabelExample;
import com.shangdiao.sd_server.generator.pojo.SdOutExp;
import com.shangdiao.sd_server.generator.pojo.SdOutExpExample;
import com.shangdiao.sd_server.generator.pojo.SdPInternshipExample;
import com.shangdiao.sd_server.generator.pojo.SdPParttimeExample;
import com.shangdiao.sd_server.generator.pojo.SdPerson;
import com.shangdiao.sd_server.generator.pojo.SdPersonBase;
import com.shangdiao.sd_server.generator.pojo.SdPersonBaseExample;
import com.shangdiao.sd_server.generator.pojo.SdPersonPhoto;
import com.shangdiao.sd_server.generator.pojo.SdPersonPhotoExample;
import com.shangdiao.sd_server.pojo.ResponseMsg;
import com.shangdiao.sd_server.pojo.Row;
import com.shangdiao.sd_server.service.DicService;
import com.shangdiao.sd_server.service.PersonService;
import com.shangdiao.sd_server.service.RedisService;
import com.shangdiao.sd_server.service.SequenceService;
import com.shangdiao.sd_server.util.CommonUtil;
import com.shangdiao.sd_server.util.DateUtil;
import com.shangdiao.sd_server.util.MD5Util;
import com.shangdiao.sd_server.util.MsgUtil;
import com.shangdiao.sd_server.util.RequestUtil;
import com.shangdiao.sd_server.util.StringUtil;

@Controller
@RequestMapping("/open/p_reg")
public class PersonLoginController {
	
	@Autowired
	DicService dicService;
	@Autowired
	PersonService personService;
	@Autowired
	RedisService redisService;
	@Autowired
	SequenceService sequenceService;
	
	@RequestMapping(value = { "/checkTel.json" })
	@ResponseBody
	public ResponseMsg checktel(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		String tel = RequestUtil.get(request, "tel");
		if(StringUtil.isBlank(tel)){
			return new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
		}
		if(!StringUtil.isMobile(tel)){
			return new ResponseMsg("手机号格式错误", ErrorCode.ERROR, null);
		}
		SdPersonBaseExample example = new SdPersonBaseExample();
		example.or().andTelEqualTo(tel).andDelEqualTo(Constant.DEL_NO);
		int count = personService.countPersonBaseByExample(example);
		
		if(count > 0){
			retMsg = new ResponseMsg("此手机号已注册！",ErrorCode.ERROR, null);
		}else{
			String auth_code = CommonUtil.genAuth_code();
			redisService.set(Constant.PERSON_TOKEN_PRE + tel, auth_code, 60 * 10);
			String content = "您的用户注册验证码为：" + auth_code;
			MsgUtil.sendMsg(tel, content);
			retMsg = new ResponseMsg("",ErrorCode.OK, null);
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/checkAuthCode.json" })
	@ResponseBody
	@Transactional
	public ResponseMsg checkAuthCode(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		String tel = RequestUtil.get(request, "tel");
		String auth_code = RequestUtil.get(request, "auth_code");
		if(StringUtil.isBlank(tel) || StringUtil.isBlank(auth_code)){
			retMsg = new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
		}else{
			if(!auth_code.equals(redisService.get(Constant.PERSON_TOKEN_PRE + tel))){
				retMsg = new ResponseMsg("验证码错误！", ErrorCode.ERROR, null);
			}else{
				redisService.del(Constant.PERSON_TOKEN_PRE + tel);
				retMsg = new ResponseMsg("", ErrorCode.OK, null);
			}
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/register.json" })
	@ResponseBody
	@Transactional
	public ResponseMsg register(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		try{
			String tel = RequestUtil.get(request, "tel");
			String pwd = RequestUtil.get(request, "pwd");
			String person_name = RequestUtil.get(request, "personName");
			String email = RequestUtil.get(request, "email");
			Integer university_id = RequestUtil.getInt(request, "universityId");
			String university = RequestUtil.get(request, "university");
			String logo = RequestUtil.get(request, "logo");
			if(StringUtil.isBlank(tel) || StringUtil.isBlank(pwd)){
				retMsg = new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
				return retMsg;
			}
			SdPersonBaseExample example = new SdPersonBaseExample();
			example.or().andTelEqualTo(tel).andDelEqualTo(Constant.DEL_NO);
			int count = personService.countPersonBaseByExample(example);
			
			if(count > 0){
				retMsg = new ResponseMsg("此手机号已注册！",ErrorCode.ERROR, null);
				return retMsg;
			}
			if(!StringUtil.isBlank(email) && !StringUtil.isEmail(email)){
				retMsg = new ResponseMsg("邮箱格式错误", ErrorCode.ERROR, null);
				return retMsg;
			}
			boolean logoFlag = true;
			if(!StringUtil.isBlank(logo)){
				logo = logo.substring(logo.lastIndexOf("/") + 1, logo.length());
				logoFlag = CommonUtil.Move(Constant.TEMP_FILE_PATH + logo, Constant.LOGO_FILE_PATH + logo);
			}
			if(logoFlag){
				Integer personId = sequenceService.nextSequence(TableConstant.SD_PERSON);
				SdPersonBase personBase = new SdPersonBase();
				personBase.setPersonId(personId);
				personBase.setPersonName(person_name);
				personBase.setPwd(MD5Util.encodeByMD5(pwd));
				personBase.setTel(tel);
				personBase.setEmail(email);
				personBase.setUniversityId(university_id);
				personBase.setUniversity(university);
				if(!StringUtil.isBlank(logo)){
					personBase.setLogo(Constant.LOGO_FILE_URL + logo);
				}
				Date createTime = new Date();
				personBase.setCreateTime(createTime);
				personService.insertPersonBase(personBase);
				SdPerson person = new SdPerson();
				person.setPersonId(personId);
				person.setPersonName(person_name);
				person.setPostFlag(Constant.POST_FLAG_PARTTIME);
				person.setTel(tel);
				person.setEmail(email);
				person.setUniversityId(university_id);
				person.setUniversity(university);
				person.setCreateTime(createTime);
				personService.insertPerson(person);
				Row result = afterLogin(personId);
				retMsg = new ResponseMsg("注册成功", ErrorCode.OK, result);
			}else{
				retMsg = new ResponseMsg("移动图片失败", ErrorCode.ERROR, null);
			}
		}catch(Exception e){
			e.printStackTrace();
			retMsg = new ResponseMsg("注册失败", ErrorCode.SERVER_ERROR, null);
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/login.json" })
	@ResponseBody
	@Transactional
	public ResponseMsg login(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		try{
			String tel = RequestUtil.get(request, "tel");
			String pwd = RequestUtil.get(request, "pwd");
			if(StringUtil.isBlank(tel) || StringUtil.isBlank(pwd)){
				retMsg = new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
				return retMsg;
			}
			SdPersonBaseExample example = new SdPersonBaseExample();
			example.or().andTelEqualTo(tel)
				.andDelEqualTo(Constant.DEL_NO);
			List<SdPersonBase> personBaselist = personService.selectPersonBaseByExample(example);
			if(personBaselist.size() == 0){
				retMsg = new ResponseMsg("该账号不存在！", ErrorCode.ERROR, null);
			}else{
				SdPersonBase personBase = personBaselist.get(0);
				if(MD5Util.encodeByMD5(pwd).equals(personBase.getPwd())){
					Integer personId = personBase.getPersonId();
					Row result = afterLogin(personId);
					retMsg = new ResponseMsg("登录成功！", ErrorCode.OK, result);
				}else{
					retMsg = new ResponseMsg("密码错误！", ErrorCode.ERROR, null);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			retMsg = new ResponseMsg("登录失败", ErrorCode.SERVER_ERROR, null);
		}
		return retMsg;
	}
	
	@RequestMapping(value = { "/findPwd.json" })
	@ResponseBody
	@Transactional
	public ResponseMsg findPwd(HttpServletRequest request, HttpServletResponse response) {
		ResponseMsg retMsg = null;
		String tel = RequestUtil.get(request, "tel");
		if(StringUtil.isBlank(tel)){
			return new ResponseMsg("缺少必要参数！", ErrorCode.ERROR, null);
		}
		SdPersonBaseExample example = new SdPersonBaseExample();
		example.or().andTelEqualTo(tel).andDelEqualTo(Constant.DEL_NO);
		List<SdPersonBase> personBaseList = personService.selectPersonBaseByExample(example);
		if(personBaseList != null && personBaseList.size() > 0){
			SdPersonBase personBase = personBaseList.get(0);
			String randomPwd = CommonUtil.genRandomPwd(6);
			personBase.setPwd(MD5Util.encodeByMD5(randomPwd));
			personService.updatePersonBaseById(personBase);
			String content = "您的个人账号登录密码已临时重置为：" + randomPwd + "，请尽快登录并重新修改密码，以保障账号安全！";
			MsgUtil.sendMsg(tel, content);
			retMsg = new ResponseMsg("",ErrorCode.OK, null);
		}else{
			retMsg = new ResponseMsg("此手机号不存在！",ErrorCode.ERROR, null);
		}
		return retMsg;
	}
	
	public Row afterLogin(Integer personId){
		String token = MD5Util.encodeByMD5(Constant.PERSON_TOKEN_PRE + personId + System.currentTimeMillis());
		redisService.set(Constant.PERSON_TOKEN_PRE + personId, token,  60 * 60 * 24 * 30);
		SdPerson person = personService.selectPersonById(personId);
		SdPersonBase personBase = personService.selectPersonBaseById(personId);
		Row result = new Row();
		result.put("identityFlag", "p");//身份标识
		result.put("uid", personId);
		result.put("token", token);
		result.put("personName", person.getPersonName());//姓名
		result.put("personGender", person.getPersonGender() == 0 ? "女" : "男");//性别
		result.put("birthday", DateUtil.DateToString(person.getBirthday(), DateUtil.LONG_DATE_FORMAT));//出生日期
		result.put("tel", person.getTel());//手机
		result.put("email", person.getEmail());//邮箱
		result.put("district", person.getDistrict());//城市
		result.put("postFlag", person.getPostFlag());//选择职位类型
		result.put("dicFieldId", person.getDicFieldId());//选择职位
		result.put("dicFieldName", person.getDicFieldName());//选择职位
		result.put("university", person.getUniversity());//学校
		result.put("college", person.getCollege());//学院
		result.put("major", person.getMajor());//专业
		result.put("admissionDate", DateUtil.DateToString(person.getAdmissionDate(), DateUtil.FORMAT_MONTH));//入学时间
		result.put("dicEducationName", person.getDicEducationName());//学历
		result.put("isInvited", person.getIsInvited());//是否接受邀请
		//头像
		String logo = personBase.getLogo();
		if(StringUtil.isBlank(logo)){
			result.put("logo", "");
		}else{
			result.put("logo", Constant.DOMAIN + logo);
		}
		//学生证
		String card = person.getCard();
		if(StringUtil.isBlank(card)){
			result.put("card", "");
		}else{
			result.put("card", Constant.DOMAIN + card);
		}
		//教育经历
		SdEduExpExample eduExpExample = new SdEduExpExample();
		eduExpExample.or().andPersonIdEqualTo(personId).andDelEqualTo(Constant.DEL_NO);
		List<SdEduExp> eduExpList = personService.selectEduExpByExample(eduExpExample);
		List<Row> eduExpRow = new ArrayList<Row>();
		for(SdEduExp eduExp : eduExpList){
			Row exp = new Row();
			exp.put("expId", eduExp.getExpId());
			exp.put("university", eduExp.getUniversity());
			exp.put("major", eduExp.getMajor());
			exp.put("during", DateUtil.DateToString(eduExp.getStartDate(), DateUtil.FORMAT_EIGHT) + "-" + DateUtil.DateToString(eduExp.getEndDate(), DateUtil.FORMAT_EIGHT));
			eduExpRow.add(exp);
		}
		result.put("eduExp", eduExpRow);
		//实践经历
		SdOutExpExample outExpExample = new SdOutExpExample();
		outExpExample.or().andPersonIdEqualTo(personId).andDelEqualTo(Constant.DEL_NO);
		List<SdOutExp> outExpList = personService.selectOutExpByExample(outExpExample);
		List<Row> outExpRow = new ArrayList<Row>();
		for(SdOutExp outExp : outExpList){
			Row exp = new Row();
			exp.put("expId", outExp.getExpId());
			exp.put("expName", outExp.getExpName());
			exp.put("desc", outExp.getDescription());
			exp.put("during", DateUtil.DateToString(outExp.getStartDate(), DateUtil.FORMAT_EIGHT) + "-" + DateUtil.DateToString(outExp.getEndDate(), DateUtil.FORMAT_EIGHT));
			outExpRow.add(exp);
		}
		result.put("outExp", outExpRow);
		//校内经历
		SdInExpExample inExpExample = new SdInExpExample();
		inExpExample.or().andPersonIdEqualTo(personId).andDelEqualTo(Constant.DEL_NO);
		List<SdInExp> inExpList = personService.selectInExpByExample(inExpExample);
		List<Row> inExpRow = new ArrayList<Row>();
		for(SdInExp inExp : inExpList){
			Row exp = new Row();
			exp.put("expId", inExp.getExpId());
			exp.put("expName", inExp.getExpName());
			exp.put("desc", inExp.getDescription());
			exp.put("during", DateUtil.DateToString(inExp.getStartDate(), DateUtil.FORMAT_EIGHT) + "-" + DateUtil.DateToString(inExp.getEndDate(), DateUtil.FORMAT_EIGHT));
			inExpRow.add(exp);
		}
		result.put("inExp", inExpRow);
		//证书技能
		SdCertificateExample certificateExample = new SdCertificateExample();
		certificateExample.or().andPersonIdEqualTo(personId).andDelEqualTo(Constant.DEL_NO);
		List<SdCertificate> certificateList = personService.selectCertificateByExample(certificateExample);
		List<Row> certificateRow = new ArrayList<Row>();
		for(SdCertificate certificate : certificateList){
			Row exp = new Row();
			exp.put("certId", certificate.getCertId());
			exp.put("certUrl", Constant.DOMAIN + certificate.getCertUrl());
			certificateRow.add(exp);
		}
		result.put("certificate", certificateRow);
		//个人标签
		SdLabelExample labelExample = new SdLabelExample();
		labelExample.or().andPersonIdEqualTo(personId).andDelEqualTo(Constant.DEL_NO);
		List<SdLabel> labelList = personService.selectLabelByExample(labelExample);
		List<Row> labelRow = new ArrayList<Row>();
		for(SdLabel label : labelList){
			Row exp = new Row();
			exp.put("labelId", label.getLabelId());
			exp.put("dicLabelName", label.getDicLabelName());
			labelRow.add(exp);
		}
		result.put("label", labelRow);
		//自我评价
		result.put("selfEvaluation", person.getSelfEvaluation());
		//个人风采
		SdPersonPhotoExample personPhotoExample = new SdPersonPhotoExample();
		personPhotoExample.or().andPersonIdEqualTo(personId).andDelEqualTo(Constant.DEL_NO);
		List<SdPersonPhoto> personPhotoList = personService.selectPersonPhotoByExample(personPhotoExample);
		List<Row> personPhotoRow = new ArrayList<Row>();
		for(SdPersonPhoto personPhoto : personPhotoList){
			Row exp = new Row();
			exp.put("personPhotoId", personPhoto.getPersonPhotoId());
			exp.put("personPhotoUrl", Constant.DOMAIN + personPhoto.getPersonPhotoUrl());
			personPhotoRow.add(exp);
		}
		result.put("personPhoto", personPhotoRow);
		//我的实习
		SdPInternshipExample pInternshipExample = new SdPInternshipExample();
		List<Integer> InternshipStatusList = new ArrayList<Integer>();
		InternshipStatusList.add(Constant.INTERNSHIP_STATUS_CHECKED);
		InternshipStatusList.add(Constant.INTERNSHIP_STATUS_INFORM);
		pInternshipExample.or().andPersonIdEqualTo(personId)
			.andStatusIn(InternshipStatusList)
			.andSourceEqualTo(Constant.SOURCE_PERSON)
			.andDelPEqualTo(Constant.DEL_NO);
		Integer myInternshipCount = personService.countPInternship(pInternshipExample);
		result.put("myInternshipCount", myInternshipCount);
		//我的兼职
		SdPParttimeExample pParttimeExample = new SdPParttimeExample();
		List<Integer> parttimeStatusList = new ArrayList<Integer>();
		parttimeStatusList.add(Constant.INTERNSHIP_STATUS_CHECKED);
		parttimeStatusList.add(Constant.INTERNSHIP_STATUS_INFORM);
		pParttimeExample.or().andPersonIdEqualTo(personId)
			.andStatusIn(parttimeStatusList)
			.andSourceEqualTo(Constant.SOURCE_PERSON)
			.andDelPEqualTo(Constant.DEL_NO);
		Integer myParttimeCount = personService.countPParttime(pParttimeExample);
		result.put("myParttimeCount", myParttimeCount);
		//机会邀约
		pParttimeExample = new SdPParttimeExample();
		pParttimeExample.or().andPersonIdEqualTo(personId)
			.andStatusEqualTo(Constant.INTERNSHIP_STATUS_APPLY)
			.andSourceEqualTo(Constant.SOURCE_COMPANY)
			.andDelPEqualTo(Constant.DEL_NO);
		myParttimeCount = personService.countPParttime(pParttimeExample);
		pInternshipExample = new SdPInternshipExample();
		pInternshipExample.or().andPersonIdEqualTo(personId)
			.andStatusEqualTo(Constant.INTERNSHIP_STATUS_APPLY)
			.andSourceEqualTo(Constant.SOURCE_COMPANY)
			.andDelPEqualTo(Constant.DEL_NO);
		myInternshipCount = personService.countPInternship(pInternshipExample);
		result.put("myInvitation", myParttimeCount + myInternshipCount);
		return result;
	}
	
	
	public static void main(String[] args) {
		
	}
	
}
